using UnityEngine;

public class ObjectRotator : MonoBehaviour
{
    [Header("Rotation Settings")]
    [Tooltip("需要旋转的目标物体（默认为自身物体）")]
    public Transform targetObject;

    [Tooltip("旋转速度（度/秒）")]
    public float rotateSpeed = 180f;

    [Header("Damping Settings")]
    [Tooltip("阻尼系数（越大停止越快）")]
    [Range(0.1f, 20f)]
    public float damping = 3f;

    [Tooltip("最小速度阈值（低于此值自动归零）")]
    public float minSpeedThreshold = 0.1f;

    [Header("Input Settings")]
    [Tooltip("顺时针旋转按键")]
    public KeyCode clockwiseKey = KeyCode.RightArrow;

    [Tooltip("逆时针旋转按键")]
    public KeyCode counterClockwiseKey = KeyCode.LeftArrow;

    [Header("Debug")]
    [Tooltip("当前实际旋转速度")]
    [SerializeField] private float currentSpeed;

    void Start()
    {
        if (targetObject == null)
        {
            targetObject = transform;
        }
    }

    void Update()
    {
        HandleInput();
        ApplyDamping();
        ApplyRotation();
    }

    void HandleInput()
    {
        if (Input.GetKey(clockwiseKey))
        {
            currentSpeed = -rotateSpeed; // 顺时针为负方向
        }
        else if (Input.GetKey(counterClockwiseKey))
        {
            currentSpeed = rotateSpeed; // 逆时针为正方向
        }
    }

    void ApplyDamping()
    {
        if (!Input.GetKey(clockwiseKey) && !Input.GetKey(counterClockwiseKey))
        {
            // 应用指数衰减
            currentSpeed *= Mathf.Clamp01(1 - damping * Time.deltaTime);

            // 当速度低于阈值时归零
            if (Mathf.Abs(currentSpeed) < minSpeedThreshold)
            {
                currentSpeed = 0f;
            }
        }
    }

    void ApplyRotation()
    {
        // 使用本地坐标系绕自身Y轴旋转
        targetObject.Rotate(Vector3.up, currentSpeed * Time.deltaTime, Space.Self);
    }

    // 辅助方法：立即停止旋转
    public void StopRotationImmediately()
    {
        currentSpeed = 0f;
    }

    // 辅助方法：设置临时旋转速度
    public void SetTemporarySpeed(float newSpeed, float duration)
    {
        StartCoroutine(TemporarySpeedCoroutine(newSpeed, duration));
    }

    private System.Collections.IEnumerator TemporarySpeedCoroutine(float newSpeed, float duration)
    {
        float originalSpeed = currentSpeed;
        currentSpeed = newSpeed;
        yield return new WaitForSeconds(duration);
        currentSpeed = originalSpeed;
    }
}